import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/mode/list_pagination_model.dart';
import 'package:flutter_smart_heating/service/auth_service.dart';
import 'package:flutter_smart_heating/ui/src/pull_to_refresh.dart';
import 'package:flutter_smart_heating/ui/ui.dart';
import 'package:get/get.dart';

class BasicEstatePage extends StatefulWidget {
  const BasicEstatePage({super.key});

  @override
  State<BasicEstatePage> createState() => _BasicEstatePageState();
}

class _BasicEstatePageState extends State<BasicEstatePage> {
  List<dynamic> list = [{}, {}, {}, {}, {}, {}, {}];
  ListPaginationModel pagination = ListPaginationModel();
  RefreshController refreshController = RefreshController();
  dynamic stationId;
  String keyword = '';
  @override
  void initState() {
    super.initState();
    stationId = Get.parameters['station_id'];
  }

  fetchData() async {
    var res = await Http.instance.post(
      '/api/basic/estate/index',
      data: {
        "page": pagination.currentPage,
        "station_id": stationId ?? 0,
        "keyword": keyword,
      },
    );

    if (res.code == 1) {
      if (pagination.currentPage <= 1) {
        list.clear();
      }
      pagination = ListPaginationModel.fromJson(res.data);
      res.data['data'].forEach(
        (item) => list.add(item),
      );
    }
    setState(() {
      list;
    });
    refreshController.refreshCompleted();
    if (pagination.hasMore) {
      refreshController.loadComplete();
    } else {
      refreshController.loadNoData();
    }
  }

  String get placeholder {
    var user = AuthService.instance.user;
    if (Get.parameters['station_name'] != null) {
      return '在${Get.parameters['station_name']}中搜索';
    }
    if (user.isSubstation == false && user.substationId! > 0) {
      return '在${user.substationName}中搜索';
    }
    return '请输入关键词';
  }

  @override
  Widget build(BuildContext context) {
    return KeyboardDismissOnTap(
      dismissOnCapturedTaps: true,
      child: Scaffold(
        appBar: AppBar(
          scrolledUnderElevation: 0,
          backgroundColor: UiTheme.of(context).match(light: Colors.white),
          title: const Text('小区信息'),
          actions: const [
            UiRightMenuButtonGroup(),
          ],
        ),
        body: UiLifeCycle(
          onRouteDone: fetchData,
          child: Column(
            children: [
              Container(
                color: UiTheme.of(context).match(
                  light: Colors.white,
                  dark: Theme.of(context).appBarTheme.backgroundColor,
                ),
                padding: const EdgeInsets.only(
                  top: UiTheme.toolbarSpacing,
                  left: UiTheme.spacingX,
                  right: UiTheme.spacingX,
                  bottom: UiTheme.spacingX,
                ),
                alignment: Alignment.centerLeft,
                child: UiSearchBar(
                  placeholder: placeholder,
                  backgroundColor:
                      UiTheme.of(context).match(light: Colors.grey[100]),
                  onSubmitted: (val) {
                    keyword = val;
                    pagination.currentPage = 1;
                    fetchData();
                  },
                  onClear: () {
                    keyword = '';
                    pagination.currentPage = 1;
                    fetchData();
                  },
                ),
              ),
              const Divider(height: 0),
              Expanded(
                child: UiPushToRefresh(
                  controller: refreshController,
                  onRefresh: () {
                    pagination.currentPage = 1;
                    fetchData();
                  },
                  enablePullUp:
                      pagination.lastPage > 1 && !refreshController.isRefresh,
                  onLoad: () {
                    pagination.currentPage++;
                    fetchData();
                  },
                  child: list.isEmpty
                      ? const Center(child: UiResult())
                      : ListView.separated(
                          separatorBuilder: (context, index) => const SizedBox(
                            height: UiTheme.spacingX,
                          ),
                          itemBuilder: (context, index) {
                            var item = list[index];
                            return itemView(item, index);
                          },
                          itemCount: list.length,
                        ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  UiOpen itemView(item, index) {
    bool isBlock = item['id'] == null;
    return UiOpen(
      url: item['url'] ?? '',
      child: UiPanel(
        height: 90,
        margin: EdgeInsets.only(
          top: index == 0 ? UiTheme.spacingX : 0,
          left: UiTheme.spacingX,
          right: UiTheme.spacingX,
        ),
        padding: const EdgeInsets.symmetric(horizontal: 15),
        child: Row(
          children: [
            Container(
              width: 14,
              height: 14,
              decoration: BoxDecoration(
                color: item['status'] == 1
                    ? Colors.blue
                    : Colors.grey.withOpacity(0.2),
                borderRadius: BorderRadius.circular(7),
              ),
            ),
            const SizedBox(width: UiTheme.spacingX),
            Expanded(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  isBlock
                      ? block(height: 22)
                      : Text(
                          item['name'] ?? '',
                          overflow: TextOverflow.ellipsis,
                          style: const TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                  const SizedBox(height: 5),
                  isBlock
                      ? block(height: 15, margin: 5, width: 200)
                      : Row(
                          children: [
                            const UiIcon(
                              UiIcons.bank,
                              size: 17,
                            ),
                            const SizedBox(width: 5),
                            if (!isBlock)
                              Text(
                                '${item['company_name']} - ${item['station_name'] ?? '--'} ',
                              )
                          ],
                        )
                ],
              ),
            ),
            const SizedBox(width: 5),
            if (item['id'] != null)
              Icon(
                Icons.arrow_forward_ios,
                color: UiTheme.of(context).listCellArrowColor,
                size: 16,
              ),
          ],
        ),
      ),
    );
  }

  Widget block({
    double? height,
    double? width,
    double? margin,
  }) {
    return Container(
      height: height,
      width: width,
      margin: EdgeInsets.symmetric(vertical: margin ?? 2),
      decoration: BoxDecoration(
        color: Colors.grey.withOpacity(0.2),
        borderRadius: BorderRadius.circular(5),
      ),
    );
  }
}
